package com.sky.controller.user;


import com.sky.constant.StatusConstant;
import com.sky.pojo.Dish;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

//    /**
//     * 根据id查询菜品
//     *
//     * @param categoryId
//     * @return
//     * 我每写一行帮我生成详细的注解
//     */
//    @GetMapping("list")
//    @ApiOperation("根据分类id查询菜品")
//    public Result<List<DishVO>> list(Long categoryId){
//        Dish dish = new Dish();//创建一个dish对象
//        dish.setCategoryId(categoryId);//设置分类id
//        dish.setStatus(StatusConstant.ENABLE);//设置状态为起售
//
//
//        List<DishVO> list = dishService.listwithFlavor(dish);//调用service层查询
//
//        return Result.success(list);//返回结果
//    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        //构造Redis的Key,规则：dish_分类id
        String key = "dish_" + categoryId;
        //查询Redis中是否有该Key对应的值
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0) {
            return Result.success(list);
        }
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        //如果不存在，则查询数据库，并将查询到的结果存入Redis
        list = dishService.listWithFlavor(dish);
        redisTemplate.opsForValue().set(key, list);
        return Result.success(list);
    }
}
